package com.leetcode.weekly.contest.no285th;

/**
 * @author 覃国强
 * @date 2022-03-20 10:31
 */
public class A01_统计数组中峰和谷的数量 {

  static
  class Solution {
    public int countHillValley(int[] nums) {
      if (nums == null || nums.length < 3) {
        return 0;
      }
      int answer = 0;
      for (int i = 1; i < nums.length; ) {
        if (nums[i] != nums[i - 1]) {
          int right = nextBound(nums, i);
          if (right == -1) {
            break;
          }
          if (nums[i] < nums[i - 1] && nums[i] < nums[right]) {
            ++answer;
          }
          if (nums[i] > nums[i - 1] && nums[i] > nums[right]) {
            ++answer;
          }
          i = right;
        } else {
          ++i;
        }
      }
      return answer;
    }

    private int nextBound(int[] nums, int i) {
      for (int j = i + 1; j < nums.length; ++j) {
        if (nums[i] != nums[j]) {
          return j;
        }
      }
      return -1;
    }
  }

}
